#include <dlfcn.h>
#include <errno.h>
#include <libcapsicum.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>


typedef int (*opensig)(const char*, int, ...);

int open(const char *path, int flags, ...)
{
	struct lc_fdlist *fds = lc_fdlist_global();

	int i;
	for(i = 0; ;)
	{
		char *subsystem = "org.freebsd.capsh";
		char *classname = "FileArgument";
		char *name;
		int fd;

		if (lc_fdlist_lookup(fds, subsystem, classname, &name, &fd, &i) < 0)
			break;

		if (strncmp(path, name, strlen(path)) == 0) return fd;
	}


	/* We didn't find the file in our FD list. If we're in a sandbox, die. */
	if(ld_insandbox())
	{
		errno = ENOENT;
		return (-1);
	}
	/* If we're not in a sandbox, try the normal open(2). */
	else
	{
		opensig real_open = (opensig) dlfunc(RTLD_NEXT, "open");

		va_list varargs;
		va_start(varargs, flags);

		int result = real_open(path, flags, varargs);

		int cached_error = errno;
		va_end(varargs);
		errno = cached_error;

		return result;
	}
}

int _open(const char *path, int flags, ...)
{
	va_list argp;
	va_start(argp, flags);

	int result = open(path, flags, argp);

	va_end(argp);

	return result;
}

